//
//  FLMakeMixingViewController.m
//  FeeLing
//
//  Created by 乔光玉 on 2019/1/11.
//  Copyright © 2019年 大仙儿飘. All rights reserved.
//
#import "JDLTabBarController.h"
#import "FLAnainNameView.h"
#import "SKVoiceWaveView.h"
#import "SFDualWaySlider.h"
#import "FLAudioObject.h"
#import "FLAudioMusicDBManager.h"
#import "FLMakeMixingViewController.h"
#import "FLpinjielingshengView.h"
@interface FLMakeMixingViewController ()
{
    CGFloat statrone;
    CGFloat endone;
    CGFloat statrtwo;
    CGFloat endtwo;
    BOOL isdayufourty;
    BOOL isdayufourtytwo;
    CGFloat touletime;//一共的时间
    CGFloat touletime1;
    CGFloat touletime2;
    FLAnainNameView * _sanainview;
    BOOL _isPlaying;
    BOOL _isfirstjiaru;
    FLpinjielingshengView * oneView ;
    FLpinjielingshengView * twoView ;
    UIView * shengchengview;
    CAGradientLayer * gl;
    NSURL * addone;
    NSURL *addtwo;
    FLAudioObject * audiothree ;
}
typedef void(^success)(BOOL ret);
@property (nonatomic, copy)success block;
@property (nonatomic,strong) AVPlayerItem *playerItem;
@property (nonatomic,strong) AVPlayer *auPlayer;
@property(nonatomic,strong) UIButton * selectedbutton;
//视频1剪裁
@property(nonatomic,strong) UIButton * playButtonone;
@property(nonatomic,strong) UIButton * addButtonone;
@property(nonatomic,strong) UILabel * begintimeone;
@property(nonatomic,strong) UILabel * endtimeone;
@property(nonatomic,strong) UILabel * cutLabelone;
@property(nonatomic,strong)NSURL * songURLone;
@property(nonatomic,strong)NSString * musicPathone ;

//视频2剪裁
@property(nonatomic,strong) UIButton * playButtontwo;
@property(nonatomic,strong) UIButton * addButtontwo;
@property(nonatomic,strong) UILabel * begintimetwo;
@property(nonatomic,strong) UILabel * endtimetwo;
@property(nonatomic,strong) UILabel * cutLabeltwo;
@property(nonatomic,strong)NSURL * songURLtwo;
@property(nonatomic,strong)NSString * musicPathtwo ;
@property (nonatomic,strong)FLAudioObject * model;

@property(nonatomic,strong) UIButton * backButton;
@property(nonatomic,strong)UIView * navView;
@property(nonatomic,strong)UILabel * navLabel;
@property(nonatomic,strong) UIButton * bringButton;
@property(nonatomic,strong) UIButton * pinjieplay;
@property(nonatomic,strong)NSURL * musicPaththree;
@property (nonatomic, strong)NSMutableArray * twourls;
@end

@implementation FLMakeMixingViewController
-(void)backButtonclick{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#2B2D5C"];
    _twourls = [NSMutableArray array];
    
    self.navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 64)];
    self.navView.backgroundColor = [UIColor colorWithHexString:@"32346A"];
    [self.view addSubview:self.navView];
    
    self.navLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, SCREENWIDTH, 25)];
    self.navLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 18];
    self.navLabel.textAlignment = NSTextAlignmentCenter;
    self.navLabel.textColor = [UIColor whiteColor];
    self.navLabel.text = NSLocalizedString(@"yinyuepinjie", nil);
    [self.view addSubview:self.navLabel];
    
    _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backButton setImage:[UIImage imageNamed:@"返回首页_slices"] forState:UIControlStateNormal];
    _backButton.frame = CGRectMake(12, 29, 27, 27);
    [_backButton addTarget:self action:@selector(backButtonclick) forControlEvents:UIControlEventTouchUpInside];
    if (SCREENHEIGHT>800) {
        self.navView.frame = CGRectMake(0, 0, SCREENWIDTH, 64+20);
        self.navLabel.frame =CGRectMake(0, 30+20, SCREENWIDTH, 25) ;
        self.backButton.frame =CGRectMake(12, 20+29, 27, 27) ;
    }
    [self.view addSubview:_backButton];
    
    UIImageView * bottomimageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, SCREENHEIGHT-56, SCREENWIDTH, 56)];
    [bottomimageview setImage:[UIImage imageNamed:@"我的背景"]];
    [self.view addSubview:bottomimageview];
    
    self.playButtonone = [UIButton new];
    self.playButtonone.frame =CGRectMake(22,111,32,32);
   
    [self.playButtonone setImage:[UIImage imageNamed:@"剪裁音频播放"] forState:UIControlStateNormal];
    [self.playButtonone setImage:[UIImage imageNamed:@"剪裁音频暂停"] forState:UIControlStateSelected];
    [self.playButtonone addTarget:self action:@selector(palyButtonclick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.playButtonone];
    
    self.addButtonone = [UIButton new];
    self.addButtonone.frame =CGRectMake(SCREENWIDTH-23-28,113,28,28);
    [self.addButtonone setImage:[UIImage imageNamed:@"添加"] forState:UIControlStateNormal];
    
    [self.addButtonone addTarget:self action:@selector(addButtonclick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.addButtonone];
    
    self.begintimeone = [[UILabel alloc]initWithFrame:CGRectMake(75, 85, 40, 14)];
    self.begintimeone.text = @"00:00";
    self.begintimeone.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 10];
    self.begintimeone.textColor = [UIColor colorWithHexString:@"#B19ADA"];
    self.begintimeone.textAlignment= NSTextAlignmentLeft;
    [self.view addSubview:self.begintimeone];
    statrone =0;
    
    self.endtimeone = [[UILabel alloc]initWithFrame:CGRectMake(self.view.width-75-40, 85, 40, 14)];
    AVAsset * avasset = self.beforeAVAsset[0];
    CGFloat ttime =CMTimeGetSeconds(avasset.duration);
    
    self.endtimeone.text =[self getMMSSFromSS:(int)ttime];
    self.endtimeone.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 10];
    self.endtimeone.textColor = [UIColor colorWithHexString:@"#B19ADA"];
    self.endtimeone.textAlignment= NSTextAlignmentRight;
    [self.view addSubview:self.endtimeone];
    
    self.cutLabelone = [[UILabel alloc]initWithFrame:CGRectMake(self.view.width-75-40, 155, 40, 14)];
    self.cutLabelone.text =[self getMMSSFromSS:(int)ttime];
    self.cutLabelone.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 10];
    self.cutLabelone.textColor = [UIColor colorWithHexString:@"#B19ADA"];
    self.cutLabelone.textAlignment= NSTextAlignmentRight;
    [self.view addSubview:self.cutLabelone];
    
    UIView *waveViewviewone = [[UIView alloc] init];
    waveViewviewone.frame = CGRectMake(60, 105, self.view.width-120, 44);
    
    waveViewviewone.backgroundColor = [UIColor colorWithHexString:@"#24234F"];
    waveViewviewone.layer.cornerRadius = 8;
    waveViewviewone.clipsToBounds = YES;
    [self.view addSubview:waveViewviewone];
    SKVoiceWaveView * waveView = [[SKVoiceWaveView alloc]initWithFrame:CGRectMake(60, 105, self.view.width-120, 44)];
    waveView.backgroundColor = [UIColor clearColor];
    //waveView.path = [[NSBundle mainBundle] pathForResource:@"beat" ofType:@"aiff" inDirectory:nil];//指定路径
    //  waveView.url = [NSBundle URLForResource:@"李荣浩 - 老街" withExtension:@"mp3" subdirectory:nil inBundleWithURL:[NSBundle mainBundle].bundleURL];//指定URL
    waveView.asset = avasset; //指定媒体
    
    waveView.lineWidth = 0;//线宽，默认0，0则为连续的视图，可测试
    waveView.lineColor = [UIColor colorWithHexString:@"#6E7370"];//颜色，默认灰色
    waveView.lineDistance = 4;//线之间的距离，默认4
    [self.view addSubview:waveView];
    
   
    
    double max =CMTimeGetSeconds(avasset.duration) ;
    
    
    SFDualWaySlider * slider = [[SFDualWaySlider alloc] initWithFrame:CGRectMake(60, 105, self.view.width-120, 44) minValue:0 maxValue:(int)max blockSpaceValue:0];
    
    slider.sliderValueChanged = ^(CGFloat minValue, CGFloat maxValue) {
        if (isdayufourty) {
            isdayufourty = NO;
            
            return ;
        }
        int difference = (int)maxValue-(int)minValue;
        self.begintimeone.text = [self getMMSSFromSS:(int)minValue];
        self.endtimeone.text =  [self getMMSSFromSS:(int)maxValue];
        self.cutLabelone.text=[self getMMSSFromSS:difference];
        statrone = (int)minValue;
        endone = (int)maxValue;
    };
    if (max>40) {
        isdayufourty = YES;
        endone = 40.00;
        slider.currentMaxValue = 40;
        self.cutLabelone.text=@"00:40";
    }else{
        isdayufourty =NO;
        endone = max;
    }
    
    
    
    
    [self.view addSubview:slider];
    
    
    
    UIImageView * line1 =[[UIImageView alloc]init];
    line1.frame = CGRectMake(15, 180, SCREENWIDTH-30, 5);
    
    [self.view addSubview:line1];
    [self drawLineByImageView:line1];
    
    
    
    self.playButtontwo = [UIButton new];
    self.playButtontwo.frame =CGRectMake(22,220,32,32);
    
    [self.playButtontwo setImage:[UIImage imageNamed:@"剪裁音频播放"] forState:UIControlStateNormal];
    [self.playButtontwo setImage:[UIImage imageNamed:@"剪裁音频暂停"] forState:UIControlStateSelected];
    [self.playButtontwo addTarget:self action:@selector(palyButtonclick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.playButtontwo];
    
    self.addButtontwo = [UIButton new];
    self.addButtontwo.frame =CGRectMake(SCREENWIDTH-23-28,223,28,28);
    [self.addButtontwo setImage:[UIImage imageNamed:@"添加"] forState:UIControlStateNormal];
    
    [self.addButtontwo addTarget:self action:@selector(addButtonclick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.addButtontwo];
    
    self.begintimetwo = [[UILabel alloc]initWithFrame:CGRectMake(75, 195, 40, 14)];
    self.begintimetwo.text = @"00:00";
    self.begintimetwo.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 10];
    self.begintimetwo.textColor = [UIColor colorWithHexString:@"#B19ADA"];
    self.begintimetwo.textAlignment= NSTextAlignmentLeft;
    [self.view addSubview:self.begintimetwo];
    statrtwo =0;
    
    self.endtimetwo = [[UILabel alloc]initWithFrame:CGRectMake(self.view.width-75-40, 195, 40, 14)];
    AVAsset * avassettwo = self.beforeAVAsset[1];
    CGFloat ttimetwo =CMTimeGetSeconds(avassettwo.duration);
    
    self.endtimetwo.text =[self getMMSSFromSS:(int)ttimetwo];
    self.endtimetwo.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 10];
    self.endtimetwo.textColor = [UIColor colorWithHexString:@"#B19ADA"];
    self.endtimetwo.textAlignment= NSTextAlignmentRight;
    [self.view addSubview:self.endtimetwo];
    
    self.cutLabeltwo = [[UILabel alloc]initWithFrame:CGRectMake(self.view.width-75-40, 265, 40, 14)];
    self.cutLabeltwo.text =[self getMMSSFromSS:(int)ttimetwo];
    self.cutLabeltwo.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 10];
    self.cutLabeltwo.textColor = [UIColor colorWithHexString:@"#B19ADA"];
    self.cutLabeltwo.textAlignment= NSTextAlignmentRight;
    [self.view addSubview:self.cutLabeltwo];
    
    UIView *waveViewview = [[UIView alloc] init];
    waveViewview.frame = CGRectMake(60, 215, self.view.width-120, 44);
    
    waveViewview.backgroundColor = [UIColor colorWithHexString:@"#24234F"];
    waveViewview.layer.cornerRadius = 8;
    waveViewview.clipsToBounds = YES;
    [self.view addSubview:waveViewview];
    SKVoiceWaveView * waveViewtwo = [[SKVoiceWaveView alloc]initWithFrame:CGRectMake(60, 215, self.view.width-120, 44)];
    waveViewtwo.backgroundColor = [UIColor clearColor];
    //waveView.path = [[NSBundle mainBundle] pathForResource:@"beat" ofType:@"aiff" inDirectory:nil];//指定路径
    //  waveView.url = [NSBundle URLForResource:@"李荣浩 - 老街" withExtension:@"mp3" subdirectory:nil inBundleWithURL:[NSBundle mainBundle].bundleURL];//指定URL
    waveViewtwo.asset = avassettwo; //指定媒体
    
    waveViewtwo.lineWidth = 0;//线宽，默认0，0则为连续的视图，可测试
    waveViewtwo.lineColor = [UIColor colorWithHexString:@"#6E7370"];//颜色，默认灰色
    waveViewtwo.lineDistance = 4;//线之间的距离，默认4
    [self.view addSubview:waveViewtwo];
    
    
    
    double maxtwo =CMTimeGetSeconds(avassettwo.duration) ;
    
    
    SFDualWaySlider * slidertwo = [[SFDualWaySlider alloc] initWithFrame:CGRectMake(60,215, self.view.width-120, 44) minValue:0 maxValue:(int)maxtwo blockSpaceValue:0];
    
    slidertwo.sliderValueChanged = ^(CGFloat minValue, CGFloat maxValue) {
        if (isdayufourtytwo) {
            isdayufourtytwo = NO;
            
            return ;
        }
        int difference = (int)maxValue-(int)minValue;
        self.begintimetwo.text = [self getMMSSFromSS:(int)minValue];
        self.endtimetwo.text =  [self getMMSSFromSS:(int)maxValue];
        self.cutLabeltwo.text=[self getMMSSFromSS:difference];
        statrtwo = (int)minValue;
        endtwo = (int)maxValue;
    };
    if (maxtwo>40) {
        isdayufourtytwo = YES;
        endtwo = 40.00;
        slidertwo.currentMaxValue = 40;
        self.cutLabeltwo.text=@"00:40";
    }else{
        isdayufourtytwo =NO;
        endtwo = maxtwo;
    }
    
    
    
    
    [self.view addSubview:slidertwo];
    
    shengchengview = [[UIView alloc] init];
    shengchengview.frame = CGRectMake(15,410,SCREENWIDTH-30,175);
    
    shengchengview.layer.backgroundColor = [UIColor colorWithRed:36/255.0 green:35/255.0 blue:79/255.0 alpha:1.0].CGColor;
    shengchengview.layer.cornerRadius = 8;
    shengchengview.clipsToBounds = YES;
    shengchengview.userInteractionEnabled = YES;
    [self.view addSubview:shengchengview];
    
    self.pinjieplay = [UIButton new];
    self.pinjieplay.frame =CGRectMake(7,40,32,32);
    [self.pinjieplay setImage:[UIImage imageNamed:@"剪裁音频播放"] forState:UIControlStateNormal];
    [self.pinjieplay setImage:[UIImage imageNamed:@"剪裁音频暂停"] forState:UIControlStateSelected];
    [self.pinjieplay addTarget:self action:@selector(palyButtonclick:) forControlEvents:UIControlEventTouchUpInside];
    
    [shengchengview addSubview:self.pinjieplay];
    
    UIView * pinjieviewbottom = [[UIView alloc] init];
    pinjieviewbottom.frame = CGRectMake(45,34,shengchengview.width-90,44);
    pinjieviewbottom.layer.cornerRadius = 8;
    pinjieviewbottom.clipsToBounds = YES;
    pinjieviewbottom.backgroundColor = [UIColor colorWithHexString:@"#7C8CF8"];
    [shengchengview addSubview:pinjieviewbottom];
    
    UIView * pinjieviewline =[[UIView alloc]init];
    pinjieviewline.frame = CGRectMake(0, pinjieviewbottom.height/2-1, pinjieviewbottom.width, 2);
    pinjieviewline.backgroundColor = [UIColor colorWithHexString:@"#DFDFDF"];
    [pinjieviewbottom addSubview:pinjieviewline];
    
    
    self.bringButton = [UIButton new];
    self.bringButton.frame =CGRectMake(45,111,shengchengview.width-90,44);
    gl = [CAGradientLayer layer];
    gl.frame = CGRectMake(0,0,shengchengview.width-90,44);
    gl.startPoint = CGPointMake(0.08, 0.18);
    gl.endPoint = CGPointMake(1, 0.89);
    gl.colors = @[(__bridge id)[UIColor colorWithRed:252/255.0 green:86/255.0 blue:142/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:252/255.0 green:86/255.0 blue:142/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:246/255.0 green:55/255.0 blue:51/255.0 alpha:1.0].CGColor];
    gl.locations = @[@(0), @(0), @(1.0f)];
    gl.cornerRadius = 22;
    
    self.bringButton.backgroundColor = [UIColor colorWithHexString:@"#8184C1"];
    self.bringButton.layer.cornerRadius = 22;
    self.bringButton.clipsToBounds = YES;
    [self.bringButton setTitle:NSLocalizedString(@"bringButtontitle", nil) forState:UIControlStateNormal];
    [self.bringButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.bringButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 18];
    
    [self.bringButton addTarget:self action:@selector(bringButtonclick:) forControlEvents:UIControlEventTouchUpInside];
    
    [shengchengview addSubview:self.bringButton];
    
    _isfirstjiaru = YES;
    
}
-(void)setUpAndAddAudioAtPath:( AVAsset *)songAsset toComposition:(AVMutableComposition*)composition start:(CMTime)start dura:(CMTime)dura offset:(CMTime)offset andArray:(NSMutableArray *)audioMixParams{
    
    
    
    AVMutableCompositionTrack *track = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    NSArray<AVAssetTrack *> * audioTrackers =[songAsset tracksWithMediaType:AVMediaTypeAudio];
    
    if (0>=audioTrackers.count) {
        return;
    }
    AVAssetTrack *sourceAudioTrack = [audioTrackers objectAtIndex:0];
    
    NSError *error = nil;
    BOOL ok = NO;
    
    CMTime startTime = start;
    CMTime trackDuration = dura;
    CMTimeRange tRange =CMTimeRangeFromTimeToTime(startTime,trackDuration);
    
    
    ok =  [track insertTimeRange:tRange ofTrack:sourceAudioTrack atTime:kCMTimeZero error:&error];
}
-(NSString*)getCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"YYYYMMdd_HHmmss"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}
//传入 秒  得到  xx分钟xx秒
-(NSString *)getMMSSFromSS:(NSInteger )seconds{
    
    
    
    //format of minute
    NSString *str_minute ;
    if (seconds/60>=10) {
        str_minute = [NSString stringWithFormat:@"%ld",seconds/60];
    }else{
        str_minute = [NSString stringWithFormat:@"0%ld",seconds/60];
    }
    
    //format of second
    NSString *str_second;
    if (seconds%60>=10) {
        str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    }else{
        str_second = [NSString stringWithFormat:@"0%ld",seconds%60];
    }
    
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    
    NSLog(@"format_time : %@",format_time);
    
    return format_time;
    
}
-(void)pinjie{
    

    
                AVURLAsset *audioAsset1 = [AVURLAsset assetWithURL:addone];
                AVURLAsset *audioAsset2 = [AVURLAsset assetWithURL:addtwo];
                AVMutableComposition *composition = [AVMutableComposition composition];
                
                // 音频轨道
                AVMutableCompositionTrack *audioTrack1 = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];
                AVMutableCompositionTrack *audioTrack2 = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];

                // 音频素材轨道
                AVAssetTrack *audioAssetTrack1 = [[audioAsset1 tracksWithMediaType:AVMediaTypeAudio] firstObject];
                AVAssetTrack *audioAssetTrack2 = [[audioAsset2 tracksWithMediaType:AVMediaTypeAudio] firstObject];
                // 音频合并 - 插入音轨文件
                [audioTrack1 insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset1.duration) ofTrack:audioAssetTrack1 atTime:kCMTimeZero error:nil];
                [audioTrack2 insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset2.duration) ofTrack:audioAssetTrack2 atTime:audioAsset1.duration error:nil];

                // 合并后的文件导出 - `presetName`要和之后的`session.outputFileType`相对应。
                AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetAppleM4A];
                NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
                NSString*path=[paths objectAtIndex:0];
                 audiothree=[[FLAudioObject alloc]init];
                //audiothree.name = text;
                audiothree.localam =[NSString stringWithFormat:@"%@.m4a",[self getCurrentTimes]];
                audiothree.type = 4;
                //audio.time = [self getMMSSFromSS:(int)CMTimeGetSeconds(songAsset.duration)];
                NSString * movDirectory =  [path stringByAppendingPathComponent:
                                            audiothree.localam];

                if ([[NSFileManager defaultManager] fileExistsAtPath:movDirectory]) {
                    [[NSFileManager defaultManager] removeItemAtPath:movDirectory error:nil];
                }

                // 查看当前session支持的fileType类型
                NSLog(@"---%@",[session supportedFileTypes]);
                session.outputURL = [NSURL fileURLWithPath:movDirectory];
                session.outputFileType = AVFileTypeAppleM4A; //与上述的`present`相对应
                session.shouldOptimizeForNetworkUse = YES;   //优化网络

                [session exportAsynchronouslyWithCompletionHandler:^{
                    if (session.status == AVAssetExportSessionStatusCompleted) {

                     AVURLAsset *audioAssetyou = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:movDirectory] options:nil];
                     audiothree.time =[self getMMSSFromSS:(int)CMTimeGetSeconds(audioAssetyou.duration)];

                        self.
                        self.playerItem = [[AVPlayerItem alloc]initWithURL:[NSURL fileURLWithPath:movDirectory]];
                        self.auPlayer = [[AVPlayer alloc]initWithPlayerItem:self.playerItem];

                        [self.auPlayer play];
                        self->_isPlaying = YES;


                    } else {

                    }
                }];




//
//
//
//    CMTime startTime =CMTimeMakeWithSeconds(0,audioAsset1.duration.timescale);
//    CMTime trackDuration =audioAsset1.duration;
//
//    CMTime startTime2 =CMTimeMakeWithSeconds(0,audioAsset2.duration.timescale);
//    CMTime trackDuration2 =audioAsset1.duration;
//
//    NSMutableArray *audioMixParams = [NSMutableArray array];
//    //获取视频中的音频素材
//    [self setUpAndAddAudioAtPath:audioAsset1 toComposition:composition start:startTime dura:trackDuration offset:CMTimeMake(14*44100,44100) andArray:audioMixParams];
//
//    //获取视频中的音频素材
//    [self setUpAndAddAudioAtPath:audioAsset2 toComposition:composition start:startTime2 dura:trackDuration2 offset:CMTimeMake(14*44100,44100) andArray:audioMixParams];
//    //
//    //创建一个可变的音频混合
//    AVMutableAudioMix *maudioMix =[AVMutableAudioMix audioMix];
//    maudioMix.inputParameters =[NSArray arrayWithArray:audioMixParams];//从数组里取出处理后的音频轨道参数
//
//    NSString *tmpDir = NSTemporaryDirectory();
//    NSString * movDirectory =  [tmpDir stringByAppendingPathComponent:
//                                [NSString stringWithFormat:@"/%@.m4a",[self getCurrentTimes]]];
//
//    if([[NSFileManager defaultManager]fileExistsAtPath:movDirectory]) {
//        [[NSFileManager defaultManager]removeItemAtPath:movDirectory error:nil];
//    }
//
//    NSURL * exportURL =[NSURL fileURLWithPath:movDirectory];
//
//    //创建一个输出
//    AVAssetExportSession *exporter =[[AVAssetExportSession alloc]
//                                     initWithAsset:composition
//                                     presetName:AVAssetExportPresetAppleM4A];
//    exporter.audioMix = maudioMix;
//    exporter.outputFileType=@"com.apple.m4a-audio";
//    exporter.outputURL = exportURL;
//    [exporter exportAsynchronouslyWithCompletionHandler:^{
//
//        dispatch_async(dispatch_get_main_queue(), ^{
//            NSLog(@"Export status not yet completed. Error: %@", exporter.error.description);
//            if (exporter.status == AVAssetExportSessionStatusCompleted) {
//                NSURL * outputURL = exporter.outputURL;
//                self.playerItem=[[AVPlayerItem alloc]initWithURL:outputURL];
//                self.auPlayer = [[AVPlayer alloc]initWithPlayerItem:self.playerItem];
//                CMTime currentTime = CMTimeMake(statrone, 1);
//                CMTime currentendTime = CMTimeMake(endone, 1);
//
//                [self playMusic];
////                [self.auPlayer seekToTime:currentTime toleranceBefore:currentTime toleranceAfter:currentendTime completionHandler:^(BOOL finished) {
////
////
////                }];
//
//
//            }
//        });
//
//    }];
//
//
//
//
//
//
    
    
    
    
    
    
    
    
  
   
   
    
    
}
-(void)panduansceond{
    if (self.songURLtwo==nil) {
        AVURLAsset *videoAsset = (AVURLAsset*)self.beforeAVAsset[1];
        // NSLog(@"AVAsset URL: %@",myAsset.URL);
        CMTime startTime =CMTimeMakeWithSeconds(0,videoAsset.duration.timescale);
        CMTime trackDuration =videoAsset.duration;
        AVMutableComposition *composition =[AVMutableComposition composition];
        NSMutableArray *audioMixParams = [NSMutableArray array];
        //获取视频中的音频素材
        [self setUpAndAddAudioAtPath:videoAsset toComposition:composition start:startTime dura:trackDuration offset:CMTimeMake(14*44100,44100) andArray:audioMixParams];
        //
        //创建一个可变的音频混合
        AVMutableAudioMix *maudioMix =[AVMutableAudioMix audioMix];
        maudioMix.inputParameters =[NSArray arrayWithArray:audioMixParams];//从数组里取出处理后的音频轨道参数
        
        NSString *tmpDir = NSTemporaryDirectory();
        NSString * movDirectory =  [tmpDir stringByAppendingPathComponent:
                                    [NSString stringWithFormat:@"/%@.m4a",[self getCurrentTimes]]];
        
        if([[NSFileManager defaultManager]fileExistsAtPath:movDirectory]) {
            [[NSFileManager defaultManager]removeItemAtPath:movDirectory error:nil];
        }
        self.musicPathtwo =movDirectory;
        NSURL * exportURL =[NSURL fileURLWithPath:movDirectory];
        
        //创建一个输出
        AVAssetExportSession *exporter =[[AVAssetExportSession alloc]
                                         initWithAsset:composition
                                         presetName:AVAssetExportPresetAppleM4A];
        exporter.audioMix = maudioMix;
        exporter.outputFileType=@"com.apple.m4a-audio";
        exporter.outputURL = exportURL;
        [exporter exportAsynchronouslyWithCompletionHandler:^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"Export status not yet completed. Error: %@", exporter.error.description);
                if (exporter.status == AVAssetExportSessionStatusCompleted) {
                    NSURL * outputURL = exporter.outputURL;
                    self.songURLtwo =outputURL;
                    
                    [self pinjie];
                    
                    
                }
            });
            
        }];
    }else{
        
        [self pinjie];
        
    }
}

-(void)panduanfirst{
    
    
    if (self.songURLone==nil) {
        AVURLAsset *videoAsset = (AVURLAsset*)self.beforeAVAsset[0];
        // NSLog(@"AVAsset URL: %@",myAsset.URL);
        CMTime startTime =CMTimeMakeWithSeconds(0,videoAsset.duration.timescale);
        CMTime trackDuration =videoAsset.duration;
        AVMutableComposition *composition =[AVMutableComposition composition];
        NSMutableArray *audioMixParams = [NSMutableArray array];
        //获取视频中的音频素材
        [self setUpAndAddAudioAtPath:videoAsset toComposition:composition start:startTime dura:trackDuration offset:CMTimeMake(14*44100,44100) andArray:audioMixParams];
        //
        //创建一个可变的音频混合
        AVMutableAudioMix *maudioMix =[AVMutableAudioMix audioMix];
        maudioMix.inputParameters =[NSArray arrayWithArray:audioMixParams];//从数组里取出处理后的音频轨道参数
        
        NSString *tmpDir = NSTemporaryDirectory();
        NSString * movDirectory =  [tmpDir stringByAppendingPathComponent:
                                    [NSString stringWithFormat:@"/%@.m4a",[self getCurrentTimes]]];
        
        if([[NSFileManager defaultManager]fileExistsAtPath:movDirectory]) {
            [[NSFileManager defaultManager]removeItemAtPath:movDirectory error:nil];
        }
        self.musicPathone =movDirectory;
        NSURL * exportURL =[NSURL fileURLWithPath:movDirectory];
        
        //创建一个输出
        AVAssetExportSession *exporter =[[AVAssetExportSession alloc]
                                         initWithAsset:composition
                                         presetName:AVAssetExportPresetAppleM4A];
        exporter.audioMix = maudioMix;
        exporter.outputFileType=@"com.apple.m4a-audio";
        exporter.outputURL = exportURL;
        [exporter exportAsynchronouslyWithCompletionHandler:^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"Export status not yet completed. Error: %@", exporter.error.description);
                if (exporter.status == AVAssetExportSessionStatusCompleted) {
                    NSURL * outputURL = exporter.outputURL;
                    self.songURLone =outputURL;
                    
                    [self panduansceond];
                    
                    
                }
            });
            
        }];
    }else{
        
        [self panduansceond];
    }
}

-(void)palyButtonclick:(UIButton *)button{
    if (button==self.pinjieplay) {
        if (addone==nil&&addtwo==nil) {
            return;
        }
    }
   button.selected = !button.selected;
    
    if (self.selectedbutton != nil && self.selectedbutton != button) {
    
        self.selectedbutton.selected = NO;
        [self.auPlayer pause];
        
    
    }
    
    self.selectedbutton = button;
    if (!button.selected) {
        [self.auPlayer pause];
        self.selectedbutton =nil;
        return;
    }
    if (button==self.playButtonone) {
        
        if (self.songURLone==nil) {
            AVURLAsset *videoAsset = (AVURLAsset*)self.beforeAVAsset[0];
            // NSLog(@"AVAsset URL: %@",myAsset.URL);
            CMTime startTime =CMTimeMakeWithSeconds(0,videoAsset.duration.timescale);
            CMTime trackDuration =videoAsset.duration;
            AVMutableComposition *composition =[AVMutableComposition composition];
            NSMutableArray *audioMixParams = [NSMutableArray array];
            //获取视频中的音频素材
            [self setUpAndAddAudioAtPath:videoAsset toComposition:composition start:startTime dura:trackDuration offset:CMTimeMake(14*44100,44100) andArray:audioMixParams];
            //
            //创建一个可变的音频混合
            AVMutableAudioMix *maudioMix =[AVMutableAudioMix audioMix];
            maudioMix.inputParameters =[NSArray arrayWithArray:audioMixParams];//从数组里取出处理后的音频轨道参数
            
            NSString *tmpDir = NSTemporaryDirectory();
            NSString * movDirectory =  [tmpDir stringByAppendingPathComponent:
                                        [NSString stringWithFormat:@"/%@.m4a",[self getCurrentTimes]]];
            
            if([[NSFileManager defaultManager]fileExistsAtPath:movDirectory]) {
                [[NSFileManager defaultManager]removeItemAtPath:movDirectory error:nil];
            }
            self.musicPathone =movDirectory;
            NSURL * exportURL =[NSURL fileURLWithPath:movDirectory];
            
            //创建一个输出
            AVAssetExportSession *exporter =[[AVAssetExportSession alloc]
                                             initWithAsset:composition
                                             presetName:AVAssetExportPresetAppleM4A];
            exporter.audioMix = maudioMix;
            exporter.outputFileType=@"com.apple.m4a-audio";
            exporter.outputURL = exportURL;
            [exporter exportAsynchronouslyWithCompletionHandler:^{
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"Export status not yet completed. Error: %@", exporter.error.description);
                    if (exporter.status == AVAssetExportSessionStatusCompleted) {
                        NSURL * outputURL = exporter.outputURL;
                        self.songURLone =outputURL;
                        AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:outputURL options:nil];
                        NSString * time= [NSString stringWithFormat:@"%.2f",CMTimeGetSeconds(songAsset.duration)];
                        //NSData * data = [NSData dataWithContentsOfFile:movDirectory];
                        
                        _isPlaying = YES;
                        self.playerItem=[[AVPlayerItem alloc]initWithURL:outputURL];
                        self.auPlayer = [[AVPlayer alloc]initWithPlayerItem:self.playerItem];
                        CMTime currentTime = CMTimeMake(statrone, 1);
                        CMTime currentendTime = CMTimeMake(endone, 1);
                        
                        [self playMusic];
                        [self.auPlayer seekToTime:currentTime toleranceBefore:currentTime toleranceAfter:currentendTime completionHandler:^(BOOL finished) {
                            
                            
                        }];
                        
                    }
                });
                
            }];
        }else{
            self.playerItem=[[AVPlayerItem alloc]initWithURL:self.songURLone];
            self.auPlayer = [[AVPlayer alloc]initWithPlayerItem:self.playerItem];
            CMTime currentTime = CMTimeMake(statrone, 1);
            CMTime currentendTime = CMTimeMake(endone, 1);
            
            [self playMusic];
            [self.auPlayer seekToTime:currentTime toleranceBefore:currentTime toleranceAfter:currentendTime completionHandler:^(BOOL finished) {
                
                
            }];
            
        }
        
        
        
        
    }else if (button==self.playButtontwo){
        
      
        if (self.songURLtwo==nil) {
            AVURLAsset *videoAsset = (AVURLAsset*)self.beforeAVAsset[1];
            // NSLog(@"AVAsset URL: %@",myAsset.URL);
            CMTime startTime =CMTimeMakeWithSeconds(0,videoAsset.duration.timescale);
            CMTime trackDuration =videoAsset.duration;
            AVMutableComposition *composition =[AVMutableComposition composition];
            NSMutableArray *audioMixParams = [NSMutableArray array];
            //获取视频中的音频素材
            [self setUpAndAddAudioAtPath:videoAsset toComposition:composition start:startTime dura:trackDuration offset:CMTimeMake(14*44100,44100) andArray:audioMixParams];
            //
            //创建一个可变的音频混合
            AVMutableAudioMix *maudioMix =[AVMutableAudioMix audioMix];
            maudioMix.inputParameters =[NSArray arrayWithArray:audioMixParams];//从数组里取出处理后的音频轨道参数
            
            NSString *tmpDir = NSTemporaryDirectory();
            NSString * movDirectory =  [tmpDir stringByAppendingPathComponent:
                                        [NSString stringWithFormat:@"/%@.m4a",[self getCurrentTimes]]];
            
            if([[NSFileManager defaultManager]fileExistsAtPath:movDirectory]) {
                [[NSFileManager defaultManager]removeItemAtPath:movDirectory error:nil];
            }
            self.musicPathtwo =movDirectory;
            NSURL * exportURL =[NSURL fileURLWithPath:movDirectory];
            
            //创建一个输出
            AVAssetExportSession *exporter =[[AVAssetExportSession alloc]
                                             initWithAsset:composition
                                             presetName:AVAssetExportPresetAppleM4A];
            exporter.audioMix = maudioMix;
            exporter.outputFileType=@"com.apple.m4a-audio";
            exporter.outputURL = exportURL;
            [exporter exportAsynchronouslyWithCompletionHandler:^{
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"Export status not yet completed. Error: %@", exporter.error.description);
                    if (exporter.status == AVAssetExportSessionStatusCompleted) {
                        NSURL * outputURL = exporter.outputURL;
                        self.songURLtwo =outputURL;
                        AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:outputURL options:nil];
                        //NSString * time= [NSString stringWithFormat:@"%.2f",CMTimeGetSeconds(songAsset.duration)];
                        //NSData * data = [NSData dataWithContentsOfFile:movDirectory];
                        
                        _isPlaying = YES;
                        self.playerItem=[[AVPlayerItem alloc]initWithURL:outputURL];
                        self.auPlayer = [[AVPlayer alloc]initWithPlayerItem:self.playerItem];
                        CMTime currentTime = CMTimeMake(statrtwo, 1);
                        CMTime currentendTime = CMTimeMake(endtwo, 1);
                        
                        [self playMusic];
                        [self.auPlayer seekToTime:currentTime toleranceBefore:currentTime toleranceAfter:currentendTime completionHandler:^(BOOL finished) {
                            
                            
                        }];
                        
                    }
                });
                
            }];
        }else{
            self.playerItem=[[AVPlayerItem alloc]initWithURL:self.songURLtwo];
            self.auPlayer = [[AVPlayer alloc]initWithPlayerItem:self.playerItem];
            CMTime currentTime = CMTimeMake(statrtwo, 1);
            CMTime currentendTime = CMTimeMake(endtwo, 1);
            
            [self playMusic];
            [self.auPlayer seekToTime:currentTime toleranceBefore:currentTime toleranceAfter:currentendTime completionHandler:^(BOOL finished) {
                
                
            }];
            
        }
        
        
        
        
        
        
    }else{
       //合成播放
       
        [self panduanfirst];
        
    }
    
    
}
-(void)playMusic{
    
    [self.auPlayer play];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playToEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}
-(void)playToEnd{
    self.auPlayer = nil;
    self.playerItem = nil;
    _isPlaying = NO;
    self.selectedbutton.selected = NO;
    self.selectedbutton = nil;
    
    
}
-(void)bringButtonclick:(UIButton *)button{
    if (addone==nil&&addtwo==nil) {
        
        return;
    }
        __weak typeof(self) weakself = self;
        _sanainview = [[FLAnainNameView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        self-> _sanainview.cancelBlock = ^(UIButton * sender) {
    
    
            __strong __typeof(self) strongSelf = weakself;
            [strongSelf->_sanainview removeFromSuperview];
    
    
        };
    
        self-> _sanainview.tureBlock = ^(UIButton * _Nonnull button, NSString * _Nonnull text) {
    
            if (text.length) {
                if ([[FLAudioMusicDBManager sharedManager] isExistAudio:text]) {
    
                    [MBProgressHUD showError:NSLocalizedString(@"mingzichongfu", nil) toView:_sanainview];
    
    
                }else{
    
    AVURLAsset *audioAsset1 = [AVURLAsset assetWithURL:addone];
    AVURLAsset *audioAsset2 = [AVURLAsset assetWithURL:addtwo];
    AVMutableComposition *composition = [AVMutableComposition composition];
    
    // 音频轨道
    AVMutableCompositionTrack *audioTrack1 = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];
    AVMutableCompositionTrack *audioTrack2 = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];
    
    // 音频素材轨道
    AVAssetTrack *audioAssetTrack1 = [[audioAsset1 tracksWithMediaType:AVMediaTypeAudio] firstObject];
    AVAssetTrack *audioAssetTrack2 = [[audioAsset2 tracksWithMediaType:AVMediaTypeAudio] firstObject];
    // 音频合并 - 插入音轨文件
    [audioTrack1 insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset1.duration) ofTrack:audioAssetTrack1 atTime:kCMTimeZero error:nil];
    [audioTrack2 insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset2.duration) ofTrack:audioAssetTrack2 atTime:audioAsset1.duration error:nil];
    
    // 合并后的文件导出 - `presetName`要和之后的`session.outputFileType`相对应。
    AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetAppleM4A];
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString*path=[paths objectAtIndex:0];
    audiothree=[[FLAudioObject alloc]init];
    audiothree.name = text;
    audiothree.localam =[NSString stringWithFormat:@"%@.m4a",[self getCurrentTimes]];
    audiothree.type = 4;
    //audio.time = [self getMMSSFromSS:(int)CMTimeGetSeconds(songAsset.duration)];
    NSString * movDirectory =  [path stringByAppendingPathComponent:
                                audiothree.localam];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:movDirectory]) {
        [[NSFileManager defaultManager] removeItemAtPath:movDirectory error:nil];
    }
    
    // 查看当前session支持的fileType类型
    NSLog(@"---%@",[session supportedFileTypes]);
    session.outputURL = [NSURL fileURLWithPath:movDirectory];
    session.outputFileType = AVFileTypeAppleM4A; //与上述的`present`相对应
    session.shouldOptimizeForNetworkUse = YES;   //优化网络
    
    [session exportAsynchronouslyWithCompletionHandler:^{
        if (session.status == AVAssetExportSessionStatusCompleted) {
            
            AVURLAsset *audioAssetyou = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:movDirectory] options:nil];
            audiothree.time =[self getMMSSFromSS:(int)CMTimeGetSeconds(audioAssetyou.duration)];
            
           
                                    if ([[FLAudioMusicDBManager sharedManager] insertAudioWith:audiothree]) {
                                        dispatch_sync(dispatch_get_main_queue(), ^{
            
                                             [MBProgressHUD showError:NSLocalizedString(@"lingshengzhizuochengg", nil) toView:_sanainview];
                                        });
            
            
                                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                            __strong __typeof(self) strongSelf = weakself;
                                            [strongSelf->_sanainview removeFromSuperview];
                                            if (_isPlaying) {
            
                                                [self.auPlayer pause];
            
                                            }
                                            [[NSNotificationCenter defaultCenter] postNotificationName:@"iphonmmme"object:@(0)];
            
                                            [self.navigationController popToRootViewControllerAnimated:YES];
                                            

            
                                        });
            
                                    }else{
                                        dispatch_sync(dispatch_get_main_queue(), ^{
            
                                        [MBProgressHUD showError:NSLocalizedString(@"lingshengzhizuoshibai", nil) toView:_sanainview];
                                          });
                                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                            if (_isPlaying) {
            
                                                [self.auPlayer pause];
            
                                            }
                                            __strong __typeof(self) strongSelf = weakself;
                                            [strongSelf->_sanainview removeFromSuperview];
            
            
                                            [self.navigationController popToRootViewControllerAnimated:YES];
            
                                        });
            
                                    }
            
        } else {
                                    // 其他情况, 具体请看这里`AVAssetExportSessionStatus`.
                                    dispatch_sync(dispatch_get_main_queue(), ^{
                                    [MBProgressHUD showError:NSLocalizedString(@"lingshengzhizuoshibai", nil) toView:_sanainview];
                                      });
                                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                        if (_isPlaying) {
            
                                            [self.auPlayer pause];
            
                                        }
                                        __strong __typeof(self) strongSelf = weakself;
                                        [strongSelf->_sanainview removeFromSuperview];
            
            
                                        [self.navigationController popToRootViewControllerAnimated:YES];
            
                                    });
        }
    }];
    
    
                }
    
    
    
    
            }else{
                dispatch_sync(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:NSLocalizedString(@"pleaserut", nil) toView:_sanainview];
                  });
            }
        };
    
        [self.view addSubview:self->_sanainview];
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
-(void)secondaudioadd{
   
   
    NSString *tmpDir = NSTemporaryDirectory();
    NSString * movDirectory2 =  [tmpDir stringByAppendingPathComponent:
                                 @"/temp2.m4a"];
    [self exportPath:movDirectory2 withFilePath:self.musicPathtwo withobjFilePath:nil  withStartTime:statrtwo withEndTime:endtwo withBlock:^(BOOL ret) {
        
        if (ret) {
            addtwo = [NSURL fileURLWithPath:movDirectory2];
            if (_isfirstjiaru) {
                AVAsset * assert = [AVURLAsset URLAssetWithURL:addtwo options:nil];
                touletime1= CMTimeGetSeconds(assert.duration);
                touletime = touletime1+touletime2;
                twoView = [[FLpinjielingshengView alloc]initWithFrame:CGRectMake(45, 34, (shengchengview.width-90)/touletime*touletime1, 44) withasset:assert];
                twoView.deleBlock = ^(UITapGestureRecognizer * tap) {
                    addtwo = nil;
                    touletime1 = 0;
                    touletime = touletime1+touletime2;
                    [self->twoView removeFromSuperview];
                    self.addButtontwo.hidden = NO;
                    twoView = nil;
                    if (oneView!=nil) {
                        
                        touletime1 = touletime2;
                        touletime2 = 0;
                        oneView.frame = CGRectMake(45, 34, (shengchengview.width-90)/touletime*touletime1, 44);
                        oneView.seclte.frame = CGRectMake(oneView.width-22,0, 22, 22);
                        
                    }else{
                        touletime1 = 0;
                        touletime = 0;
                        _isfirstjiaru = YES;
                        [gl removeFromSuperlayer];
                        self.bringButton.backgroundColor = [UIColor colorWithHexString:@"#8184C1"];
                    }
                    
                };
                [shengchengview addSubview:twoView];
                self.addButtontwo.hidden = YES;
                _isfirstjiaru = NO;
                [self.bringButton.layer insertSublayer:gl atIndex:0];
                
                
            }else{
                
                AVAsset * assert = [AVURLAsset URLAssetWithURL:addtwo options:nil];
                touletime2= CMTimeGetSeconds(assert.duration);
                if (touletime1+touletime2>40) {
                    //弹框
                    
                    [MBProgressHUD showError:NSLocalizedString(@"pinjielingshengxiaoyu", nil) toView:self.view];
                    
                    touletime2=0;
                    addtwo=nil;
                    return;
                }
                touletime = touletime1+touletime2;
                oneView.frame = CGRectMake(45, 34, (shengchengview.width-90)/touletime*touletime1, 44);
                oneView.seclte.frame = CGRectMake(oneView.width-22, 0, 22, 22);
                twoView = [[FLpinjielingshengView alloc]initWithFrame:CGRectMake(45+oneView.width, 34, (shengchengview.width-90)/touletime*touletime2, 44) withasset:assert];
                twoView.deleBlock = ^(UITapGestureRecognizer * tap) {
                    addtwo = nil;
                    [self->twoView removeFromSuperview];
                    self.addButtontwo.hidden = NO;
                    touletime2 = 0;
                    touletime = touletime1 +touletime2;
                    twoView = nil;
                    oneView.frame = CGRectMake(45, 34, (shengchengview.width-90)/touletime*touletime1, 44);
                    oneView.seclte.frame = CGRectMake(oneView.width-22, 0, 22, 22);
                    
                    if (oneView==nil) {
                        touletime2 = 0;
                        touletime = 0;
                        _isfirstjiaru = YES;
                        [gl removeFromSuperlayer];
                        self.bringButton.backgroundColor = [UIColor colorWithHexString:@"#8184C1"];
                    }
                    
                };
                [shengchengview addSubview:twoView];
                self.addButtontwo.hidden = YES;
            }
        }else{
            
        }
    }];
    
}
-(void)firstaudioadd{
    
    NSString *tmpDir = NSTemporaryDirectory();
    NSString * movDirectory1 =  [tmpDir stringByAppendingPathComponent:
                                 @"/temp1.m4a"];
    [self exportPath:movDirectory1 withFilePath:self.musicPathone withobjFilePath:nil  withStartTime:statrone withEndTime:endone withBlock:^(BOOL ret) {
        
        if (ret) {
            addone = [NSURL fileURLWithPath:movDirectory1];
            if (_isfirstjiaru) {
                
                
                AVURLAsset * songAsset = [AVURLAsset URLAssetWithURL:addone options:nil];
                touletime1= CMTimeGetSeconds(songAsset.duration);
                touletime = touletime1+touletime2;
                oneView = [[FLpinjielingshengView alloc]initWithFrame:CGRectMake(45, 34, (shengchengview.width-90)/touletime*touletime1, 44) withasset:songAsset];
                oneView.deleBlock = ^(UITapGestureRecognizer * tap) {
                    addone = nil;
                    [self->oneView removeFromSuperview];
                    self.addButtonone.hidden = NO;
                    oneView = nil;
                    touletime1 = 0;
                    touletime = touletime1+touletime2;
                    if (twoView!=nil) {
                        touletime1 = touletime2;
                        touletime2 = 0;
                        twoView.frame = CGRectMake(45, 34, (shengchengview.width-90)/touletime*touletime1, 44);
                        twoView.seclte.frame = CGRectMake(twoView.width-22, 0, 22, 22);
                        
                    }else{
                        touletime1 = 0;
                        touletime = 0;
                        _isfirstjiaru = YES;
                        [gl removeFromSuperlayer];
                        self.bringButton.backgroundColor = [UIColor colorWithHexString:@"#8184C1"];
                        if (self.selectedbutton==self.pinjieplay) {
                            self.selectedbutton.selected = NO;
                            [self.auPlayer pause];
                            self.selectedbutton=nil;
                        }
                    }
                    
                    
                    
                };
                [shengchengview addSubview:oneView];
                self.addButtonone.hidden = YES;
                _isfirstjiaru = NO;
                [self.bringButton.layer insertSublayer:gl atIndex:0];
                
            }else{
                
                
                AVAsset * assert = [AVURLAsset URLAssetWithURL:addone options:nil];
                touletime2= CMTimeGetSeconds(assert.duration);
                if (touletime1+touletime2>40) {
                    //弹框
                    
                    [MBProgressHUD showError:NSLocalizedString(@"pinjielingshengxiaoyu", nil) toView:self.view];
                    
                    touletime2=0;
                    addone=nil;
                    return;
                }
                touletime = touletime1+touletime2;
                twoView.frame = CGRectMake(45, 34, (shengchengview.width-90)/touletime*touletime1, 44);
                twoView.seclte.frame = CGRectMake(twoView.width-22, 0, 22, 22);
                oneView = [[FLpinjielingshengView alloc]initWithFrame:CGRectMake(45+twoView.width, 34, (shengchengview.width-90)/touletime*touletime2, 44) withasset:assert];
                oneView.deleBlock = ^(UITapGestureRecognizer * tap) {
                    addone = nil;
                    touletime2 = 0;
                    touletime = touletime1+touletime2;
                    [self->oneView removeFromSuperview];
                    self.addButtonone.hidden = NO;
                    oneView = nil;
                    
                    if (twoView==nil) {
                        touletime1 = 0;
                        touletime = 0;
                        _isfirstjiaru = YES;
                        [gl removeFromSuperlayer];
                        self.bringButton.backgroundColor = [UIColor colorWithHexString:@"#8184C1"];
                        if (self.selectedbutton==self.pinjieplay) {
                            self.selectedbutton.selected = NO;
                            [self.auPlayer pause];
                            self.selectedbutton=nil;
                        }
                    }
                    
                    
                };
                [shengchengview addSubview:oneView];
                self.addButtonone.hidden = YES;
            }
        }else{
            
        }
    }];
    
  
   
}
-(void)addButtonclick:(UIButton *)button{
   
   
    
    if (button==self.addButtonone) {
       
            AVURLAsset *videoAsset = (AVURLAsset*)self.beforeAVAsset[0];
            // NSLog(@"AVAsset URL: %@",myAsset.URL);
            CMTime startTime =CMTimeMakeWithSeconds(0,videoAsset.duration.timescale);
            CMTime trackDuration =videoAsset.duration;
            AVMutableComposition *composition =[AVMutableComposition composition];
            NSMutableArray *audioMixParams = [NSMutableArray array];
            //获取视频中的音频素材
            [self setUpAndAddAudioAtPath:videoAsset toComposition:composition start:startTime dura:trackDuration offset:CMTimeMake(14*44100,44100) andArray:audioMixParams];
            //
            //创建一个可变的音频混合
            AVMutableAudioMix *maudioMix =[AVMutableAudioMix audioMix];
            maudioMix.inputParameters =[NSArray arrayWithArray:audioMixParams];//从数组里取出处理后的音频轨道参数
            
            NSString *tmpDir = NSTemporaryDirectory();
            NSString * movDirectory =  [tmpDir stringByAppendingPathComponent:
                                        [NSString stringWithFormat:@"/%@.m4a",[self getCurrentTimes]]];
            
            if([[NSFileManager defaultManager]fileExistsAtPath:movDirectory]) {
                [[NSFileManager defaultManager]removeItemAtPath:movDirectory error:nil];
            }
            self.musicPathone =movDirectory;
            NSURL * exportURL =[NSURL fileURLWithPath:movDirectory];
            
            //创建一个输出
            AVAssetExportSession *exporter =[[AVAssetExportSession alloc]
                                             initWithAsset:composition
                                             presetName:AVAssetExportPresetAppleM4A];
            exporter.audioMix = maudioMix;
            exporter.outputFileType=@"com.apple.m4a-audio";
            exporter.outputURL = exportURL;
            [exporter exportAsynchronouslyWithCompletionHandler:^{
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"Export status not yet completed. Error: %@", exporter.error.description);
                    if (exporter.status == AVAssetExportSessionStatusCompleted) {
                        NSURL * outputURL = exporter.outputURL;
                        self.songURLone =outputURL;
                          [self firstaudioadd];

                        
                        
                        
                    }
                });
                
            }];
        
        
        
    }else{
        
       
            AVURLAsset *videoAsset = (AVURLAsset*)self.beforeAVAsset[1];
            // NSLog(@"AVAsset URL: %@",myAsset.URL);
            CMTime startTime =CMTimeMakeWithSeconds(0,videoAsset.duration.timescale);
            CMTime trackDuration =videoAsset.duration;
            AVMutableComposition *composition =[AVMutableComposition composition];
            NSMutableArray *audioMixParams = [NSMutableArray array];
            //获取视频中的音频素材
            [self setUpAndAddAudioAtPath:videoAsset toComposition:composition start:startTime dura:trackDuration offset:CMTimeMake(14*44100,44100) andArray:audioMixParams];
            //
            //创建一个可变的音频混合
            AVMutableAudioMix *maudioMix =[AVMutableAudioMix audioMix];
            maudioMix.inputParameters =[NSArray arrayWithArray:audioMixParams];//从数组里取出处理后的音频轨道参数
            
            NSString *tmpDir = NSTemporaryDirectory();
            NSString * movDirectory =  [tmpDir stringByAppendingPathComponent:
                                        [NSString stringWithFormat:@"/%@.m4a",[self getCurrentTimes]]];
            
            if([[NSFileManager defaultManager]fileExistsAtPath:movDirectory]) {
                [[NSFileManager defaultManager]removeItemAtPath:movDirectory error:nil];
            }
            self.musicPathtwo =movDirectory;
            NSURL * exportURL =[NSURL fileURLWithPath:movDirectory];
            
            //创建一个输出
            AVAssetExportSession *exporter =[[AVAssetExportSession alloc]
                                             initWithAsset:composition
                                             presetName:AVAssetExportPresetAppleM4A];
            exporter.audioMix = maudioMix;
            exporter.outputFileType=@"com.apple.m4a-audio";
            exporter.outputURL = exportURL;
            [exporter exportAsynchronouslyWithCompletionHandler:^{
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"Export status not yet completed. Error: %@", exporter.error.description);
                    if (exporter.status == AVAssetExportSessionStatusCompleted) {
                        NSURL * outputURL = exporter.outputURL;
                        self.songURLtwo =outputURL;
                        [self secondaudioadd];
                        
                        
                    }
                });
                
            }];
        
        
    }
    
    
}
- (void)drawLineByImageView:(UIImageView *)imageView {
    UIGraphicsBeginImageContext(imageView.frame.size);   //开始画线 划线的frame
    [imageView.image drawInRect:CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)];
    //设置线条终点形状
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    
    CGContextRef line = UIGraphicsGetCurrentContext();
    // 设置颜色
    CGContextSetStrokeColorWithColor(line, [UIColor colorWithHexString:@"#616B75"].CGColor);
    
    
    CGFloat lengths[] = {5,2};//先画4个点再画2个点
    CGContextSetLineDash(line,0, lengths,2);//注意2(count)的值等于lengths数组的长度
    
    CGContextMoveToPoint(line, 0.0, 2.0);    //开始画线
    CGContextAddLineToPoint(line,imageView.frame.size.width,2.0);
    CGContextStrokePath(line);
    // UIGraphicsGetImageFromCurrentImageContext()返回的就是image
    UIImage *image =   UIGraphicsGetImageFromCurrentImageContext();
    imageView.image = image;
}



- (void)exportPath:(NSString *)exportPath

      withFilePath:(NSString *)filePath withobjFilePath:(NSString *)objfilePath


     withStartTime:(float)startTime

       withEndTime:(float)endTime

         withBlock:(success)handle

{
    
    _block = handle;
    
    
    
    NSString *presetName;
    
    NSString *outputFileType;
    
    
    
    if ([filePath.lastPathComponent containsString:@"m4a"]){
        
        
        
        presetName = AVAssetExportPresetAppleM4A;
        
        outputFileType = AVFileTypeAppleM4A;
        
        
        
    }else{
        
        
        
        _block(NO);   return;
        
    }
    
    
    
    // 1.拿到预处理音频文件
    
    NSURL *songURL = [NSURL fileURLWithPath:filePath];
    
    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:songURL options:nil];
    
    
    
    // 2.创建新的音频文件
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {
        
        [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
        
    }
    
    
    
    CMTime _startTime = CMTimeMake(startTime*1000, 1000);
    CMTime _stopTime = CMTimeMake(endTime*1000, 1000);
    AVMutableComposition *composition =[AVMutableComposition composition];
    NSMutableArray *audioMixParams = [NSMutableArray array];
    //获取视频中的音频素材
    [self setUpAndAddAudioAtPath:songAsset toComposition:composition start:_startTime dura:_stopTime offset:CMTimeMake(14*44100,44100) andArray:audioMixParams];
    
    //创建一个可变的音频混合
    AVMutableAudioMix *audioMix =[AVMutableAudioMix audioMix];
    audioMix.inputParameters =[NSArray arrayWithArray:audioMixParams];//从数组里取出处理后的音频轨道参数
    
    //创建一个输出
    AVAssetExportSession *exporter =[[AVAssetExportSession alloc]
                                     initWithAsset:composition
                                     presetName:AVAssetExportPresetAppleM4A];
    exporter.audioMix = audioMix;
    exporter.outputFileType=@"com.apple.m4a-audio";
    
    
    if([[NSFileManager defaultManager]fileExistsAtPath:exportPath]) {
        [[NSFileManager defaultManager]removeItemAtPath:exportPath error:nil];
    }
    
    NSURL *exportURL =[NSURL fileURLWithPath:exportPath];
    exporter.outputURL = exportURL;
    
    
    __weak typeof(self) weakSelf = self;
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Export status not yet completed. Error: %@", exporter.error.description);
            if (exporter.status == AVAssetExportSessionStatusCompleted) {
                NSURL *songURL = [NSURL fileURLWithPath:exportPath];
                
                AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:songURL options:nil];
                
                NSData * data = [NSData dataWithContentsOfFile:exportPath];
                NSLog(@"data:%@",data);
                NSNumber *size;
                [songAsset.URL getResourceValue:&size forKey:NSURLFileSizeKey error:nil];
                
                
                    strongSelf-> _block(YES);
               
                
            }else{
                
                strongSelf-> _block(NO);
                
            }
        });
        
        
    }];
    
    
}

@end
